package test;
 
import java.awt.Graphics;
import java.awt.Point;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JFrame;

import org.reference.generic.information.Gene;
import org.reference.generic.operator.Node;
 
public class TreeDraw extends JFrame {
	private static final long serialVersionUID = 1L;
	private static final int DISTANCE = 50;
	private Node root;
	private int arity;
	
	public TreeDraw(Gene gene) {
		root = gene.getRootNode();
		arity = root.getArity();
		setBounds(100, 100, 640, 480);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
	
	Map<String, String> depthCalc = new HashMap<String, String>();
	
	@Override
	public void paint(Graphics g) {
		super.paint(g);
		depthCalc.clear();
		g.drawString(root.getName(), DISTANCE, DISTANCE);
		drawChild(g, root, new Point(DISTANCE, DISTANCE));
	}
	
	private void drawChild(Graphics g, Node node, Point parentPosition) {
		Point myPosition = drawMe(g, node, parentPosition);
		if(!node.isTerminal()) {
			for(int i = 0; i < arity; i++) 
				drawChild(g, node.getChild(i), myPosition);
		} 
	}

	private Point drawMe(Graphics g, Node node, Point parentPosition) {
		String key = String.valueOf(node.getDepth());
		int childNumber = 0;
		if(depthCalc.containsKey(key)) {
			childNumber = Integer.valueOf(depthCalc.get(key));
			childNumber++;
			depthCalc.put(key, String.valueOf(childNumber));
		} else {
			depthCalc.put(key, String.valueOf(childNumber));
		}
		
		int x = childNumber * DISTANCE * 2 + DISTANCE;
		int y = node.getDepth() * DISTANCE * 2 + DISTANCE;
		g.drawString(node.getName(), x, y);
		g.drawLine(parentPosition.x, parentPosition.y, x, y);
		return new Point(x, y);
	}
}